<?php
namespace Service\Library;

/**
 * Parse ini config
 */
class LibConfig
{
    private static $env = 'dev';
    private static $configs = [];
    private static $levels = [
        'service' => APP_PATH . '/../service/config/',
        'app' => APP_PATH . '/config/'
    ];

    public static function setEnv($env)
    {
        $env && self::$env = $env;
    }

    public static function get($config_file, $var = null)
    {
        $config = [];

        $configs = self::loadFile($config_file);
        if($configs) {
            if($var) {
                isset($configs[$var]) && $config = $configs[$var];
            } else {
                $config = $configs;
            }
        }

        return $config;
    }

    private static function loadFile($config_file)
    {
        $configs = [];

        if(isset(self::$configs[$config_file])) {
            $configs = self::$configs[$config_file];
        } else {
            foreach(self::$levels as $k => $v) {
                $file_path = "{$v}{$config_file}.ini";
                if(!file_exists($file_path)) {
                    continue;
                }

                $configs = parse_ini_file($file_path, true);
                if($configs) {
                    break;
                }
            }
            self::$configs[$config_file] = $configs = isset($configs[self::$env]) ? $configs[self::$env] : [];
        }

        return $configs;
    }
}